//
//  YLScannerViewController.m
//  YLScaner
//
//  Created by Admin on 2025/9/28.
//

#import "YLScannerViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "YLMultipleResultView.h"
#import "QRCodeScannerView.h"


@interface YLScannerViewController ()<AVCaptureMetadataOutputObjectsDelegate>

@property (nonatomic, strong) AVCaptureSession *captureSession;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;
// 是否暂时扫描动画
@property (nonatomic, assign) BOOL animated;

// 多结果
@property (nonatomic, strong) YLMultipleResultView *resultView;
// 导航栏
@property (nonatomic, strong) UIView *navBarView;
// 导航栏
@property (nonatomic, strong) UIView *previewView;
// 动画视图
@property (nonatomic, strong) QRCodeScannerView *scannerView;

@end

@implementation YLScannerViewController

/// 是否展示动画
- (instancetype)initWithAnimated:(BOOL)animated{
    
    self = [super init];
    if (self) {
        self.animated = animated;
    }
    
    return self;
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    // 检查权限
    [self checkCameraPermission];
}
- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor blackColor];
    
    // 设置导航栏
    [self createNaviBar];
    
    // 是否暂时动画
    if (self.animated) {
        
        [self setupScannerView];
    }
}

- (void)setupScannerView {
    
    self.scannerView = [[QRCodeScannerView alloc] initWithFrame:self.view.bounds];
    [self.previewView addSubview:self.scannerView];
}

// 开始动画
- (void)startAnimation{
    
    [self.scannerView startScanAnimation];
    [self.captureSession startRunning];
}
// 停止动画
- (void)stopAnimation{
    
    [self.scannerView stopScanAnimation];
    [self.captureSession stopRunning];
}


// 创建导航栏
- (void)createNaviBar {
    
    // 预览视图
    self.previewView = [UIView.alloc initWithFrame:self.view.bounds];
    [self.view addSubview:self.previewView];
    
    // 导航栏视图
    CGFloat navBarX = 0;
    CGFloat navBarY = 0;
    CGFloat navBarW = self.view.frame.size.width;
    CGFloat navBarH = getStatusBarHeight() + 44;
    UIView *navBar = [[UIView alloc] initWithFrame:CGRectMake(navBarX, navBarY, navBarW, navBarH)];
    [self.view addSubview:navBar];
    self.navBarView = navBar;
    
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, navBarH - 44, 60, 44);
    [backButton setImage:[self backImageColor:UIColor.whiteColor lineWidth:2] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(clickBack) forControlEvents:UIControlEventTouchUpInside];
    [navBar addSubview:backButton];
    
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.frame = CGRectMake(navBarW / 2 - 30, navBarH - 44, 60, 44);
    titleLabel.font = [UIFont systemFontOfSize:18];
    titleLabel.text = @"扫一扫";
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [navBar addSubview:titleLabel];
}
- (void)clickBack {
    
    if (self.presentingViewController) {
        if (self.navigationController) {
            [self.navigationController dismissViewControllerAnimated:YES completion:nil];
        }else {
            [self dismissViewControllerAnimated:YES completion:nil];
        }
    }else {
        
        [self.navigationController popViewControllerAnimated:YES];
    }
}
// 初始化扫描器
- (void)checkCameraPermission {
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (granted) {
                [self setupCaptureSession];
            } else {
                [self showCameraPermissionDeniedAlert];
            }
        });
    }];
}

- (void)setupCaptureSession {
    
    // 回话对象
    self.captureSession = [[AVCaptureSession alloc] init];
    
    // 配置输入设备
    AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    NSError *error = nil;
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:&error];
    
    if (input && [self.captureSession canAddInput:input]) {
        
        [self.captureSession addInput:input];
        
        // 配置元数据输出
        AVCaptureMetadataOutput *metadataOutput = [[AVCaptureMetadataOutput alloc] init];
        
        if ([self.captureSession canAddOutput:metadataOutput]) {
            
            [self.captureSession addOutput:metadataOutput];
            
            // 设置代理和队列
            [metadataOutput setMetadataObjectsDelegate:self queue:dispatch_queue_create("com.barcode.scanner", DISPATCH_QUEUE_SERIAL)];
            
            // 配置支持的条码类型（主流码制）
            metadataOutput.metadataObjectTypes = @[
                AVMetadataObjectTypeQRCode,               // QR码
                AVMetadataObjectTypeDataMatrixCode,       // Data Matrix
                AVMetadataObjectTypePDF417Code,           // PDF417
                AVMetadataObjectTypeCode128Code,          // Code 128
                AVMetadataObjectTypeEAN13Code,            // EAN-13
                AVMetadataObjectTypeEAN8Code,             // EAN-8
                AVMetadataObjectTypeCode39Code,           // Code 39
                AVMetadataObjectTypeAztecCode             // Aztec
            ];
            
            // 设置扫描区域（基于设备坐标）
            [self setupScanRegion:metadataOutput];
            
            // 配置预览层
            [self setupPreviewLayer];
            
            // 启动会话
//            [self.captureSession startRunning];
            [self startAnimation];
        } else {
            [self showErrorWithMessage:@"无法添加元数据输出"];
        }
    } else {
        [self showErrorWithMessage:error.localizedDescription ?: @"无法访问摄像头"];
    }
}

- (void)setupPreviewLayer {
    
    self.previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
    self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
//    self.previewLayer.frame = self.view.bounds;
//    [self.view.layer insertSublayer:self.previewLayer atIndex:0];
    
    self.previewLayer.frame = self.previewView.bounds;
    [self.previewView.layer insertSublayer:self.previewLayer atIndex:0];
}

- (void)setupScanRegion:(AVCaptureMetadataOutput *)output {
    
    // 将扫描框坐标转换为AVFoundation的坐标系统（原点在右上角，取值范围0-1设置扫描框大小为屏幕中间的正方形区域
    CGFloat scanSize = MIN(self.view.bounds.size.width, self.view.bounds.size.height) * 0.7;
    CGRect scanRect = CGRectMake((self.view.bounds.size.width - scanSize) / 2,(self.view.bounds.size.height - scanSize) / 2,scanSize,scanSize);
    
    // 转换坐标
    CGFloat x = scanRect.origin.y / self.view.bounds.size.height;
    CGFloat y = scanRect.origin.x / self.view.bounds.size.width;
    CGFloat width = scanRect.size.height / self.view.bounds.size.height;
    CGFloat height = scanRect.size.width / self.view.bounds.size.width;
    output.rectOfInterest = CGRectMake(x, y, width, height);
    
    //    output.rectOfInterest = self.view.bounds;
}

#pragma mark - AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)output didOutputMetadataObjects:(NSArray<__kindof AVMetadataObject *> *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    
    
    if (metadataObjects.count > 1) {
        
        
        if (metadataObjects.count == 1)
        {
            
            // 单结果识别
            __weak typeof(self) weakSelf = self;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [weakSelf stopAnimation];
                
                AVMetadataMachineReadableCodeObject *metadataObject = metadataObjects.firstObject;
                if (weakSelf.scanResultCallback) {
                    
                    weakSelf.scanResultCallback(metadataObject.stringValue);
                }else{
                    [weakSelf showResultWithMessage:metadataObject.stringValue];
                }
            });
            
        }else
        {
            
            // 单结果识别
            __weak typeof(self) weakSelf = self;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [weakSelf stopAnimation];
                
                NSMutableArray *tempArr = NSMutableArray.array;
                for (AVMetadataObject *metadataObject in metadataObjects)
                {
                    // 步骤1：获取元数据对象在视频帧中的归一化矩形（0~1范围）
                    CGRect metadataRect = metadataObject.bounds;
                    
                    // 步骤2：将视频帧坐标转换为预览层的图层坐标（实际像素/点坐标）
                    // 注意：使用 previewLayer 的 layerRectConverted(fromMetadataOutputRect:) 方法
                    CGRect layerRect = [weakSelf.previewLayer rectForMetadataOutputRectOfInterest:metadataRect];
                    
                    // 对象封装
                    [tempArr addObject:[NSValue valueWithCGRect:layerRect]];
                }
                
                
                [weakSelf onRemoveResultView];
                weakSelf.navBarView.hidden = YES;
                
                weakSelf.resultView = [YLMultipleResultView.alloc initWithFrame:weakSelf.view.bounds];
                [weakSelf.view addSubview:weakSelf.resultView];
                
                // 设置回调
                [self.resultView updateMultipleResult:tempArr
                                       resultCallback:^(NSUInteger index) {
                    
                    AVMetadataMachineReadableCodeObject *metadataObject = metadataObjects[index];
                    if (weakSelf.scanResultCallback) {
                        
                        weakSelf.scanResultCallback(metadataObject.stringValue);
                        [weakSelf clickBack];
                    }else{
                        [weakSelf showResultWithMessage:metadataObject.stringValue];
                    }
                } closeCallback:^{
                    
                    [weakSelf onRemoveResultView];
                    weakSelf.navBarView.hidden = NO;
                    [weakSelf startAnimation];
                }];
            });
            
        }
        
    }
}


- (void)onRemoveResultView {
    if (self.resultView) {
        [self.resultView removeFromSuperview];
        self.resultView = nil;
    }
}



#pragma mark - 懒加载
- (UIModalPresentationStyle)modalPresentationStyle{
    
    return UIModalPresentationFullScreen;
}

#pragma mark - 弹出框
- (void)showCameraPermissionDeniedAlert {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"权限不足"
                                                                   message:@"请在设置中允许应用访问摄像头以使用扫描功能"
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    __weak typeof(self) weakSelf = self;
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf clickBack];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)showErrorWithMessage:(NSString *)message {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"错误"
                                                                   message:message
                                                            preferredStyle:UIAlertControllerStyleAlert];
    __weak typeof(self) weakSelf = self;
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [weakSelf clickBack];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)showResultWithMessage:(NSString *)message {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"结果"
                                                                   message:message
                                                            preferredStyle:UIAlertControllerStyleAlert];
    __weak typeof(self) weakSelf = self;
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [weakSelf clickBack];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}
// 返回箭头
- (UIImage *)backImageColor:(UIColor *)color lineWidth:(CGFloat)lineWidth {
    
    CGSize size = CGSizeMake(24, 24);
    UIGraphicsBeginImageContextWithOptions(size, NO, 0);
    
    // 画箭头
    UIBezierPath *arrowPath = [UIBezierPath bezierPath];
    [arrowPath moveToPoint:CGPointMake(18, 4)];
    [arrowPath addLineToPoint:CGPointMake(9, 12)];
    [arrowPath addLineToPoint:CGPointMake(18, 20)];
    
    arrowPath.lineWidth = lineWidth;
    arrowPath.lineCapStyle = kCGLineCapRound;
    arrowPath.lineJoinStyle = kCGLineJoinRound;
    [color setStroke];
    [arrowPath stroke];
    
    // 5. 从上下文获取图像
    UIImage *arrowImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // 6. 结束图形上下文
    UIGraphicsEndImageContext();
    
    return arrowImage;
}




@end
